package com.xyw.code.study202007281.processor;

import com.xyw.code.study202007281.enums.OrderType;
import com.xyw.code.study202007281.handler.OrderHandlerBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: xuyiwei
 * Date: 2020/7/29
 * Time: 上午9:09
 * Email: 1328312923@qq.com
 * Description: No Description
 **/
@Component
@Slf4j
public class HandlerProcessor implements BeanFactoryPostProcessor {

    private String PACKAGE = "com.xyw.code.study202007281";

    /**
     * 在初始化bean工厂之前 住的
     * @param beanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        //先定义一个放置的map
        Map<String,  Class> handlerMap = ClassScaner.scan(PACKAGE, OrderType.class).stream().collect(Collectors.toMap(
                clazz->{ return clazz.getAnnotation(OrderType.class).source();},
                Function.identity()
        ));
        //先定义一个放置的map
        Map<OrderHandlerBO,  Class> handlerOrderMap = ClassScaner.scan(PACKAGE, OrderType.class).stream().collect(Collectors.toMap(
                clazz->{ return OrderHandlerBO.builder().payMethod(clazz.getAnnotation(OrderType.class).payMethod()).source(clazz.getAnnotation(OrderType.class).source()).build();},
                Function.identity()
        ));
        //最后注册到实体类
        HandlerContext context = new HandlerContext(handlerMap);
        HandlerPayMethodContext payMethodContext = new HandlerPayMethodContext(handlerOrderMap);

        beanFactory.registerSingleton(HandlerPayMethodContext.class.getName(),payMethodContext);
        beanFactory.registerSingleton(HandlerContext.class.getName(),context);
    }
}
